package com.yuyu.commons.toolKit;

import lombok.AccessLevel;
import lombok.NoArgsConstructor;
import org.springframework.beans.BeansException;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.stereotype.Component;

/**
 * @author 获取
 * @version 1.0
 * @description:  从ioc容器中获取对象
 * @date 2022/8/2 16:54
 */
@Component
@NoArgsConstructor(access = AccessLevel.PRIVATE)
public class ApplicationUtils implements ApplicationContextAware {

    private static ApplicationContext context;


    @Override
    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
             ApplicationUtils.context=applicationContext;
    }

    /**
     * 获取context
     * @return context
     */
    public static ApplicationContext getContext(){
        return context;
    }


    /**
     * 根据名字来获取bean
     * @param name
     * @param <T>
     * @return
     */
    @SuppressWarnings("unchecked")
    public static  <T> T getBeanByName(String name){
        return (T) context.getBean(name);
    }


    /**
     * 根据类型来获取bean
     * @param clazz
     * @param <T>
     * @return
     */
    public static  <T> T getBeanByClass(Class<T> clazz){
        return (T) context.getBean(clazz);
    }


    /**
     * 判断是否存在bean
     * @param name
     * @return
     */
    public static Boolean isContainsBean(String name){
        return context.containsBean(name);
    }

}
